import java.util.*;
public class ShortestJobFirst extends Scheduler{
	public void run(){
		check_new();
		while(!queue.isEmpty() || !processes.isEmpty()){
			if(!queue.isEmpty()){
				queue.get(0).wait_time += time - queue.get(0).last_access;
				if(queue.get(0).last_access == 0)
					System.out.println("[Time: " + time + "ms][Process "  + queue.get(0).id + "|Burst Time: " + queue.get(0).burst + "ms|Wait time: " + queue.get(0).wait_time + "ms] is accessing the CPU for the first time");
				else
					System.out.println("[Time: " + time + "ms][Process "  + queue.get(0).id + "|Remaining Burst: " + queue.get(0).burst + "ms|Wait time: " + queue.get(0).wait_time + "ms] is accessing the CPU");
				while(queue.get(0).burst > 0){
					queue.get(0).burst--;
					time++;
					check_new();
				}
				queue.get(0).turnaround_time = time - queue.get(0).arrival;
				turnaround_times.add(queue.get(0).turnaround_time);
				wait_times.add(queue.get(0).wait_time);
	        	System.out.println("[Time: " + time + "ms][Context Switch][Process " + queue.get(0).id + "|Wait Time: " + queue.get(0).wait_time + "ms|Turnaround Time " + (time - queue.get(0).arrival) + "ms] has been terminated");
	        	context_switch();
	        	context_switch_count++;
				if(!(queue.size() <= 1 || !processes.isEmpty()))
					check_new();
				queue.remove(0);
				Collections.sort(queue, new Burst_Comparison());
			}
			else{
				time++;
				check_new();
			}
		}
		print_stats();
	}
	public void context_switch(){
		time += 3;
    	context_switch_time += 3;
	}
	public void check_new(){
		while(!processes.isEmpty() && processes.get(0).arrival <= time){
			queue.add(processes.get(0));
			System.out.println("[Time: " + time + "ms][Process " + processes.get(0).id + "|Burst Time: " + processes.get(0).burst + "ms] added to queue");
			processes.remove(0);
		}
		if(!queue.isEmpty()){
			Process p = queue.get(0);
			Collections.sort(queue, new Burst_Comparison());
			if(queue.get(0) != p){
				for(int i = 0; i < queue.size(); i++)
					if(queue.get(i) == p)
						queue.get(i).last_access = time;
				if(time != 0){
					System.out.println("[Time: " + time + "ms][Context Switch][Process " + p.id + "|Remaining Burst: " + p.burst + "ms] swapped out for [Process " + queue.get(0).id + "|Remaining Burst: " + queue.get(0).burst + "ms|Wait Time: " + queue.get(0).wait_time + "ms]");
					context_switch();
					context_switch_count++;
				}
			}
		}
	}
}
